package com.google.code.toub.waves.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * Inspired from http://github.com/technohippy/robot_multiplexer/blob/master/
 * robot_multiplexer.py
 * 
 * @author ntoublanc
 * 
 */
public class MultiplexingServlet extends HttpServlet {
	/**
	 * Serial version UID
	 */
	private static final long serialVersionUID = -8706985314710811901L;

	private static final Map<String, Servlet> DELEGATE_SERVLETS = new HashMap<String, Servlet>();
	static {
		// first servlet is the default servlet
		DELEGATE_SERVLETS.put("toub-demo.appspot.com",
				new RemoveExpiredBlipsServlet("Remove expired blips"));
		DELEGATE_SERVLETS.put("test.toub-demo.appspot.com",
				new RemoveExpiredBlipsServlet("Remove expired blips TEST"));
	}

	/**
	 * @param req
	 * @param res
	 * @throws ServletException
	 * @throws IOException
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse)
	 */
	@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {

		Servlet delegateServlet = null;

		if (req instanceof HttpServletRequest) {
			HttpServletRequest httpReq = (HttpServletRequest) req;
			if (httpReq != null && httpReq.getRequestURL() != null) {
				for (Entry<String, Servlet> delegateServletEntry : DELEGATE_SERVLETS
						.entrySet()) {
					if (httpReq.getRequestURL().toString().contains(
							delegateServletEntry.getKey())) {
						// url matches
						delegateServlet = delegateServletEntry.getValue();
						break;
					}
				}
			}
		}
		if (delegateServlet == null) {
			// default servlet
			delegateServlet = DELEGATE_SERVLETS.values().iterator().next();
		}
		// delegate service
		delegateServlet.service(req, res);
	}

}
